from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.models.AdminRolePermission import AdminRolePermission
from app.models.AdminPermission import AdminPermission
from app.models.AdminRole import AdminRole
from masonite.facades import Session
from app.models.AdminActionLog import AdminActionLog
from app.my_package.MyPackage import MyValidator


class AdminRolePermissionController(Controller):
    uri  = "/admin/role-permission"
    temp = "admin.role-permission"

    def index(self, request: Request, view: View):
        admin_role_id = request.input('admin_role_id')
        data = {
            'title': MyControllerTrait.get_permission_title(self.uri + '/index'),
            'uri': self.uri,
            'admin_role_id': admin_role_id
        }
        return view.render(self.temp + ".index", data)

    def show(self, request:Request, response: Response):
        admin_role_id = request.input("admin_role_id")
        b, m = MyValidator.is_integer(int(admin_role_id))
        if b is False:
            return response.redirect(location=self.uri+'/index', status=302)

        role_permissions = []
        if len(admin_role_id) > 0:
            role_permissions = AdminRolePermission.handle_checked(admin_role_id, AdminPermission.get_permission())

        data = {
            'code': 1,
            'message': 'success',
            'data': role_permissions
        }
        return response.json(data)

    def store(self, request: Request, response: Response):
        permission_ids = request.input("permission_ids[]")
        admin_role_id = request.input("admin_role_id")

        b, m = MyValidator.is_integer(int(admin_role_id))
        if b is False:
            return response.json({'code': 0, 'message': '角色ID' + m})

        admin_role = AdminRole.where('id', admin_role_id).first()
        if admin_role is None:
            return response.json({'code': 0, 'message': '未知角色'})

        AdminRolePermission.where('admin_role_id', admin_role_id).delete()
        ids = AdminPermission.get_ids()
        for permission_id in permission_ids:
            if int(permission_id) in ids:
                AdminRolePermission.generate_log(admin_role_id, permission_id)
        remark = MyControllerTrait.get_permission_title(request.get_path())
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})
